#!/bin/bash

set -x

# default to update source then build

TOP_DIR=$(pwd)
SRC_DIR=$TOP_DIR/lib_source
BD_DIR=$TOP_DIR/lib_build
BIN_DIR=$TOP_DIR/lib_bin

cmd=all64
if [ -n "$1" ] ; then
	cmd=$1
fi

if [ "$cmd" == "all64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "update" ] ; then
	mkdir -p $SRC_DIR || exit 0
	cd $SRC_DIR
	if [ ! -d qtbase-opensource-src-5.1.0 ] ; then
		wget http://download.qt-project.org/official_releases/qt/5.1/5.1.0/submodules/qtbase-opensource-src-5.1.0.tar.gz
		tar xzf qtbase-opensource-src-5.1.0.tar.gz
	fi
	cd ..
fi

export PATH=$TOP_DIR/cross/bin:$PATH

if [ "$cmd" == "all64" ] || [ "$cmd" == "b64" ] || [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
	CROSS_PREFIX="x86_64-w64-mingw32-"
	if [ "$cmd" == "all32" ] || [ "$cmd" == "b32" ] ; then
		CROSS_PREFIX="i686-w64-mingw32-"
	fi
	rm -rf $BIN_DIR/qt5
	mkdir -p $BD_DIR
	cd $BD_DIR
	rm -rf bd_qt5
	mkdir bd_qt5
	cd bd_qt5

	# <1> build qtbase
	patch -d $SRC_DIR/qtbase-opensource-src-5.1.0 -p0 < $TOP_DIR/patch/qt5-w64.patch
	$SRC_DIR/qtbase-opensource-src-5.1.0/configure \
		-prefix $BIN_DIR/qt5 -opensource -confirm-license \
		-release -shared -xplatform win32-g++ \
		-device-option CROSS_COMPILE=$CROSS_PREFIX \
		-opengl desktop -no-glib \
		-nomake examples -nomake tests \
		-v

	make $MAKE_OPT
	make install
	strip $BIN_DIR/qt5/bin/qmake
	patch -d $SRC_DIR/qtbase-opensource-src-5.1.0 -p0 -R < $TOP_DIR/patch/qt5-w64.patch

	# <1.5> build native qmake/moc/uic/rcc
	cp -R $SRC_DIR/qtbase-opensource-src-5.1.0/qmake qmake_w64
	cp -R $SRC_DIR/qtbase-opensource-src-5.1.0/src/tools/moc moc_w64
	cp -R $SRC_DIR/qtbase-opensource-src-5.1.0/src/tools/uic uic_w64
	cp -R $SRC_DIR/qtbase-opensource-src-5.1.0/src/tools/rcc rcc_w64
	cp -R $SRC_DIR/qtbase-opensource-src-5.1.0/src/tools/qdoc qdoc_w64
	patch -p0 < $TOP_DIR/patch/qt5-native-tool.patch

	cd qmake_w64
	../bin/qmake qmake.pro
	make 
	cp ../bin/qmake.exe $BIN_DIR/qt5/bin/
	cd ..

	cd moc_w64
	../bin/qmake moc.pro
	make 
	cp release/moc.exe $BIN_DIR/qt5/bin/
	cd ..

	cd uic_w64
	../bin/qmake uic.pro
	make
	cp release/uic.exe $BIN_DIR/qt5/bin/
	cd ..

	cd rcc_w64
	../bin/qmake rcc.pro
	make
	cp release/rcc.exe $BIN_DIR/qt5/bin/
	cd ..

	cd qdoc_w64
	../bin/qmake qdoc.pro
	make
	cp release/qdoc.exe $BIN_DIR/qt5/bin/
	cd ..

	# <2> build qtimage format

	cd ..
	cd ..
fi

